package logic

import (
	"common"
	"common/configx"
	"common/zapx"
	"errors"
	"github.com/minio/minio-go/v7"
	"go.uber.org/zap"
	"google.golang.org/protobuf/types/known/timestamppb"
	"minio/internal/pb"
	"minio/internal/pkg/miniox"
	"time"
)

// CompleteUpload 完成上传
func CompleteUpload(fileName, fileMd5 string, data []byte, opt minio.PutObjectOptions) (*pb.UploadResponse, error) {
	//计算一下md5值对不对
	md5Value := common.Md5FileByBytes(data)
	if md5Value != fileMd5 {
		return nil, errors.New("数据md5不相等")
	}
	//写出文件
	mn := miniox.Instance()
	//上传文件
	res, err := mn.PutBytes(fileName, data, opt)
	if err != nil {
		return nil, err
	}
	uri, _ := GetUriByKey(res.Key)
	return &pb.UploadResponse{
		Key:          res.Key,
		Size:         res.Size,
		Uri:          uri,
		LastModified: timestamppb.New(res.LastModified),
		Expiration:   timestamppb.New(res.Expiration),
	}, nil
}

// GetUriByKey 获取 key
func GetUriByKey(key string) (uri string, err error) {
	mn := miniox.Instance()
	return mn.ParseUri(key), nil
}

// ObjectExists 对象是否存在
func ObjectExists(objectName string) error {
	mn := miniox.Instance()
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	_, err := mn.StatObject(ctx, configx.C.Minio.BucketName, objectName, minio.StatObjectOptions{})
	if err != nil {
		zapx.Logger.Error("检查文件失败", zap.Error(err))
		return errors.New("文件不存在")
	}
	return nil
}
